<?php

namespace Logistics;

/**
 *快递100Api接口
 */

class Logistics
{
    // private $key = 'VmKOHJKb5999';        //请求url。
    private $key = 'hgEuSljX459';        //请求url。

    // private $customer = 'EDE78C99E23530C46DEF4BE9CE93F4FB';    //appcode
    private $customer = 'F4CA4CB1CD8B2BD11020A229339DE659';    //appcode

    //若实例化的时候传入相应的值则按新的相应值进行
    public function __construct($key = null, $customer = null)
    {
        if ($key) $this->key = $key;
        if ($customer) $this->customer = $customer;
    }
    /**
     *查询快递信息接口
     */
    public function getlogistics($com, $num, $phone = '', $from = '', $to = '')
    {
        $param = array(
            'com' => $com,              //快递公司编码
            'num' => $num,              //快递单号
            'phone' => $phone,          //手机号
            'from' => $from,            //出发地城市
            'to' => $to,                //目的地城市
            'resultv2' => '1'           //开启行政区域解析
        );
        $data = $this->curl($this->customer,$param,$this->key);
        return $data;
    }
    /**
     *Curl方法
     */
    public function curl($customer = "", $param = "", $key = "")
    {
        //请求参数
        $post_data = array();
        $post_data["customer"] = $customer;
        $post_data["param"] = json_encode($param);
        $sign = md5($post_data["param"] . $key . $post_data["customer"]);
        $post_data["sign"] = strtoupper($sign);
        $url = 'http://poll.kuaidi100.com/poll/query.do';    //实时查询请求地址
        $params = "";
        foreach ($post_data as $k => $v) {
            $params .= "$k=" . urlencode($v) . "&";        //默认UTF-8编码格式
        }
        $post_data = substr($params, 0, -1);
        //发送post请求
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($ch);
        $data = str_replace("\"", '"', $result);
        return $data;
    }
}
